<template>
  <div class="app-container">
    <!--搜索框-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="ID">
        <el-input v-model="queryParams.id" placeholder="请输入学号" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <el-input v-model="queryParams.username" placeholder="请输入学员姓名" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="queryParams.idcard" placeholder="请输入学员身份证" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号码" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工种" prop="subject_id">
        <el-cascader size="small" v-model="queryParams.subjectId" :options="typeList" placeholder="选择工种" :props="{
          value: 'id',
          label: 'courseName',
          children: 'childrenList',
          expandTrigger: 'hover',
        }" :show-all-levels="false" clearable @change="handleCascaderChange"></el-cascader>
      </el-form-item>
      <el-form-item label="职级" prop="grade_id">
        <el-select v-model="queryParams.gradeId" placeholder="请选择">
          <el-option v-for="item in gradeList" :key="item.id" :label="item.grade" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="class_id">
        <el-select v-model="queryParams.classId" placeholder="请选择">
          <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="培训状态" prop="state_id">
        <el-select v-model="queryParams.state" placeholder="请选择">
          <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="培训类型" prop="parent_id">
        <el-select v-model="queryParams.subjectParentId" placeholder="请选择">
          <el-option v-for="item in parentList" :key="item.id" :label="item.label" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格上方按钮 -->
    <div>
      <div style="float: left">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出选中学员</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportAll">导出全部学员</el-button>
        <el-button type="primary" plain icon="el-icon-upload" size="mini" @click="handleImportByClass">按班级导入学员</el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDeleteSelected">删除选中学员</el-button>
        <el-button type="success" plain icon="el-icon-people" size="mini" @click="handleAddStudent">批量分班</el-button>
        <el-tag type="success">学员总人数：{{ total }}</el-tag>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"
        style="float: right"></right-toolbar>
    </div>
    <!-- 表格数据 -->
    <el-table border v-loading="loading" :data="studentList" @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#FAFAFA' }" height="75vh">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" width="50" align="center" header-align="center" label="序号" />
      <el-table-column label="学号" prop="user.id" v-if="columns[0].visible" />
      <el-table-column label="姓名" prop="user.username" v-if="columns[1].visible" />
      <el-table-column label="证件号码" prop="user.idcard" v-if="columns[2].visible">
        <template slot-scope="scope">{{
          scope.row.user.idcard ? scope.row.user.idcard : "---"
        }}</template>
      </el-table-column>
      <el-table-column label="手机号码" prop="user.mobile" v-if="columns[3].visible">
        <template slot-scope="scope">{{
          scope.row.user.mobile ? scope.row.user.mobile : "---"
        }}</template>
      </el-table-column>
      <el-table-column label="性别" prop="user.sex" v-if="columns[4].visible">
        <template slot-scope="scope">
          <span>{{ scope.row.user.sex === 1 ? '女' : scope.row.user.sex === 2 ? '男' : '---' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="user.age" v-if="columns[5].visible">
        <template slot-scope="scope">{{
          scope.row.user.age ? scope.row.user.age : "---"
        }}</template>
      </el-table-column>
      <el-table-column label="班级名称" prop="user.classname" v-if="columns[6].visible">
        <template slot-scope="scope">{{
          scope.row.user.classname ? scope.row.user.classname : "---"
        }}</template></el-table-column>
      <el-table-column label="职级" prop="user.grade" v-if="columns[14].visible">
        <template slot-scope="scope">{{
          scope.row.user.grade ? scope.row.user.grade : "---"
        }}</template></el-table-column>
      <el-table-column label="工种" prop="user.subjectname" v-if="columns[7].visible">
        <template slot-scope="scope">{{
          scope.row.user.subjectname ? scope.row.user.subjectname : "---"
        }}</template></el-table-column>
      <el-table-column label="已学时长(分钟)" prop="user.learnTime" v-if="columns[8].visible">
        // 若learn_time为空,则显示“未开始”
        <template slot-scope="scope">
          <span v-if="scope.row.user.learnTime">{{ scope.row.user.learnTime }}</span>
          <span v-else>未开始</span>
        </template>
      </el-table-column>
      <el-table-column label="课程学习进度(%)" prop="user.progress" v-if="columns[9].visible"></el-table-column>
      <el-table-column label="是否完成学习" prop="is_pass" v-if="columns[10].visible">
        <template slot-scope="scope">
          <span v-if="scope.row.user.progress == 100" style="color: green">已完成</span>
          <span v-else style="color: rgb(231, 231, 87)">未完成</span>
        </template>
      </el-table-column>

      <!-- 状态：如果为true，显示禁用按钮和状态信息，如果为false，显示启用按钮 -->
      <el-table-column label="账号状态" v-if="columns[11].visible" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.user.isDisabled == false">启用</span>
          <span v-if="scope.row.user.isDisabled == true">禁用</span>
          <el-button v-if="scope.row.user.isDisabled == false" type="danger" size="mini" plain
            @click="handleStatus(scope.row.user)">禁用</el-button>
          <el-button v-if="scope.row.user.isDisabled == true" type="success" size="mini" plain
            @click="handleStatus(scope.row.user)">启用</el-button>
        </template>
      </el-table-column>
      <el-table-column label="学员状态" prop="stateName" v-if="columns[12].visible">
        <template slot-scope="scope">{{
          scope.row.stateName ? scope.row.stateName : "---"
        }}</template></el-table-column>
      <el-table-column label="备注" prop="user.remark" v-if="columns[13].visible">
        <template slot-scope="scope">{{
          scope.row.user.remark ? scope.row.user.remark : "无"
        }}</template></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="columns[14].visible">
        <template slot-scope="scope" v-if="scope.row.userId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row.user)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="viewVideoRecord(scope.row.user)">视频记录</el-button>
          <el-button size="mini" type="text" icon="el-icon-view"
            @click="viewCertificates(scope.row.user)">证书记录</el-button>
          <el-button size="mini" type="text" icon="el-icon-view"
            @click="viewQuestionRecord(scope.row.user)">做题记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div style="width: 100%; text-align: center; margin-top: 10px">
      <el-pagination @size-change="sizeChange" @current-change="goto" :current-page="page" :page-sizes="[50, 100, 150, 200]"
        :page-size="limit" layout="total, sizes, prev, pager, next, jumper" :total="total" background
        style="float: right">
      </el-pagination>
    </div>
    <!-- 新增用户信息 -->
    <el-dialog title="新增学员" :visible.sync="addDialog" width="30%">
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入学员姓名" maxlength="30" />
        </el-form-item>

        <!-- <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            placeholder="请输入学员密码"
            prop="password"
          />
        </el-form-item> -->
        <el-form-item label="身份证号" prop="idcard">
          <el-input v-model="addForm.idcard" placeholder="请输入学员身份证号" maxlength="30" />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入学员姓名" maxlength="30" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idcard">
          <el-input v-model="form.idcard" placeholder="请输入学员身份证号" maxlength="30" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入学员手机号码" maxlength="11" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :min="1" :max="150" label="年龄"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio :label="2">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="学员状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择">
            <el-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注信息" prop="remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看学习时长 -->
    <el-dialog title="学员学习时长" :visible.sync="timeDialog" width="30%">
      <span>{{ Math.round(studyTime / 3600) }} 小时</span>
      <span>{{ Math.round((studyTime % 3600) / 60) }} 分钟</span>
      <span>{{ studyTime % 60 }}秒 </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="timeDialog = false">取 消</el-button>
        <el-button type="primary" @click="timeDialog = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload2.title" :visible.sync="upload2.open" width="400px" append-to-body>
      <span>
        在此导入的学员将直接加入该班级
        <br />导入后，系统将自动生成学员的登录账户
        <br />账号：身份证号或手机号，初始密码：123456</span>
        <el-divider></el-divider>
        <label>选择导入班级：</label>
        <el-select v-model="importClass" placeholder="请选择导入的班级">
          <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id">
          </el-option>
        </el-select>
        <el-divider></el-divider>
      <!-- 
        下方的:headers="upload.headers"是为了解决跨域问题，如果不需要跨域，可以去掉
      -->
      <el-upload ref="upload2" :limit="1" accept=".xlsx, .xls" :action="upload2.newurl" :disabled="upload2.isUploading"
        :on-progress="handleFileUploadProgress2" :on-success="handleFileSuccess2" :on-exceed="handleFileExceed2"
        :auto-upload="false" :before-upload="handleFileBefore" drag >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            href="https://school-file-mjzx.oss-cn-guangzhou.aliyuncs.com/ExcelTemplate/batchImportStudentsTemplate.xlsx">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm2">确 定</el-button>
        <el-button @click="upload2.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量分班 -->
    <el-dialog title="批量分班" :visible.sync="addDialog2" width="60%">
      <!--搜索框-->
      <el-form :model="addQueryParams" size="small" :inline="true" label-width="70px">
        <el-form-item label="学号" prop="studentId">
          <el-input
            v-model="addQueryParams.id"
            placeholder="请输入学员学号"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="studentName">
          <el-input
            v-model="addQueryParams.username"
            placeholder="请输入学员姓名"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="studentName">
          <el-input
            v-model="addQueryParams.idcard"
            placeholder="请输入学员身份证"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="addQueryParams.mobile"
            placeholder="请输入手机号码"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getAddList"
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="resetAddList"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <label>选择分入的班级：</label>
      <el-select v-model="selectedClassId" placeholder="请选择需要分入的班级">
          <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id">
          </el-option>
        </el-select>
      <el-table
        border
        v-loading="loading"
        :data="addQueryList"
        @selection-change="handleSelectionChange2"
        :header-cell-style="{ background: '#FAFAFA' }"
        class="addDialog2"
      >
        <el-table-column type="selection" width="50" align="center" />
        <!-- <el-table-column
          label="学员id"
          prop="id"
          :show-overflow-tooltip="true"
        /> -->
        <el-table-column label="学号" prop="id" :show-overflow-tooltip="true" />
        <el-table-column label="姓名" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="身份证号" prop="idcard" :show-overflow-tooltip="false" />
        <el-table-column label="手机号码" prop="mobile" :show-overflow-tooltip="true" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog2 = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd2">添加选中学员</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryList,
  removeStudent,
  updateInfo,
  addInfo,
  getStudyTime,
  getAllStudentList,
  removeStudentSelected,
  getUnClassStudentList
} from "@/api/student";
import { getGrade } from "@/api/edu/course";
import { getClassStudent, updateClassMember } from "@/api/class/classStudent";
import { getCategory, getClassList } from "@/api/classification";
import { mapGetters } from "vuex";
import * as XLSX from 'xlsx';
export default {
  name: "StudentList",
  components: {},
  computed: {
    ...mapGetters(["companyId"]),
  },
  data () {
    return {
      // 表格加载遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 批量删除时非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总记录数
      total: 1,
      // 学生用户表格数据
      studentList: null,
      //查看学习时长对话框
      timeDialog: false,
      //学习时长
      studyTime: 0,
      // 修改对话框标题
      title: "",
      // 是否显示修改对话框
      open: false,
      //添加对话框
      addDialog: false,
      addDialog2: false,
      //添加信息表单
      addForm: {},
      addForm2: {},
      // 修改信息表单参数
      form: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: "",
      },
      // 表格分页参数
      page: 1,
      limit: 50,
      // 查询参数
      queryParams: {
        id: undefined,
        username: undefined,
        mobile: undefined,
        idcard: undefined,
        classId: undefined,
        subjectId: undefined,
        gradeId:undefined
      },
      // 展示的列信息
      columns: [
        { key: 0, label: `学号`, value: 'id', visible: true },
        { key: 1, label: `姓名`, value: 'username', visible: true },
        { key: 2, label: `证件号码`, value: 'idcard', visible: true },
        { key: 3, label: `手机号码`, value: 'mobile', visible: true },
        { key: 4, label: `性别`, value: 'sex', visible: true },
        { key: 5, label: `年龄`, value: 'age', visible: true },
        { key: 6, label: `班级名称`, value: 'classname', visible: true },
        { key: 7, label: `工种`, value: 'subjectname', visible: true },
        { key: 8, label: `已学时长`, value: 'learnTime', visible: true },
        { key: 9, label: `课程学习进度`, value: 'progress', visible: true },
        { key: 10, label: `是否完成学习`, value: 'is_pass', visible: true },
        { key: 11, label: `账号状态`, value: 'isDisabled', visible: true },
        { key: 12, label: `状态`, value: 'stateName', visible: true },
        { key: 13, label: `备注`, value: 'remark', visible: true },
        { key: 14, label: `职级`, value: 'grade', visible: true },
        { key: 15, label: `操作`, visible: true },
      ],
      //添加表单验证
      addRules: {
        username: [
          { required: true, message: "学员姓名不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "学员姓名长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        idcard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "学员密码长度必须介于 6 和 20 之间",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 修改表单校验
      rules: {
        username: [
          { required: true, message: "学员姓名不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "学员姓名长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        idcard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 选中的学员
      selectedRows: [],
      // 全部学员列表
      allStudentList: [],
      //类别列表
      typeList: [],
      // 班级列表
      classList: [],
      // 学员状态列表
      stateList: [
        { label: "培训中", value: '0' },
        { label: "已结业", value: '1' },
        { label: "已退学", value: '2' },
        { label: "已休学", value: '3' }
      ],
      // 培训状态列表
      parentList:[],
      // 用户导入参数
      upload2: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.BASE_API +
        "/eduM2/eduClass/batchImportClassStudent/",
        newurl: "",
      },
      // 选择导入的班级对象
      importClass: null,
      importInfo:{
        id:'',
        companyId:'',
        grade:'',
        subjectId:''
      },
      // 职级列表
      gradeList: [],
      //班级学生列表查询
      addQueryParams: {
        id: null,
        username: null,
        idcard: null,
        mobile: null,
      },
      //新增学生列表查询
      addQueryList: null,
      //选中班级id
      selectedClassId: null,
    };
  },
  watch: {},
  created () {
    this.getList();
    this.initUploadUrl();
    this.getCategoryList(this.companyId);
    this.getClassListMethod(this.companyId);
    this.getGradeList();
  },
  methods: {
    // 初始化上传Excel的URL
    initUploadUrl () {
      this.upload.url =
        process.env.BASE_API +
        "/edu/student/batchImportStudent/" +
        this.companyId;
    },
    /** 查询用户列表 */
    getList () {
      this.loading = true;
      // console.log(this.queryParams);
      queryList(this.page, this.limit, this.queryParams, this.companyId).then(
        (response) => {
          this.studentList = response.data.rows;
          console.log(this.studentList)
          //console.log(response.data);
          this.total = response.data.total;
          //console.log(this.studentList);
          this.studentList.forEach((item) => {
            item.progress = item.progress * 100;
            item.is_pass = item.progress == 100 ? "已完成" : "未完成";
            // 若sex值为1则设置为女，sex值为2则设置为男
            if (item.sex == 1) item.sex = '女'
            else if (item.sex == 2) item.sex = '男'
          });
          this.loading = false;
        }
      );
    },
    // 表单重置
    reset () {
      this.addForm = {
        username: undefined,
        idcard: undefined,
        password: undefined,
        mobile: undefined,
      };
      this.resetForm("addForm");
    },
    /** 重置按钮操作 按照当前分页的位置，重新进行请求*/
    resetQuery () {
      this.queryParams = {
        id: undefined,
        username: undefined,
        mobile: undefined,
        idcard: undefined,
        classId: undefined,
        subjectId: undefined,
      };
      this.getList();
    },
    // 表单重置
    resetForm (refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.user.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      // 对selection进行遍历，将user对象赋值给selectedRows
      this.selectedRows = [];
      selection.forEach((item) => {
        item.user.stateName = item.stateName;
        this.selectedRows.push(item.user);
      });
      //console.log(this.selectedRows)
    },
    // 多选框选中学员
    handleSelectionChange2(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.selectedRows = selection;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.addForm.companyId = this.companyId;
      this.addDialog = true;
    },
    handleAddStudent(){
      this.reset2();
      this.addDialog2 = true;
      this.getAddList();
    },
    reset2() {
      this.addForm2 = {
        username: undefined,
        idcard: undefined,
        password: undefined,
        mobile: undefined,
      };
      this.resetForm("addForm2");
    },
    submitAdd () {
      this.addForm.password = "123456";
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          addInfo(this.addForm).then((response) => {
            this.addDialog = false;
            this.getList();
            // 成功提示
            this.$message({
              message: "添加成功",
              type: "success",
              duration: 1000,
            });
          });
        }
      });
    },
    //提交修改
    submitAdd2() {
      // 判断selectedClassId是否为空
      if (this.selectedClassId == null) {
        this.$message({
          message: "请选择需要分入的班级",
          type: "warning",
        });
        return;
      }
      // 判断ids是否为空
      if (this.ids.length == 0) {
        this.$message({
          message: "请选择需要分入的学员",
          type: "warning",
        });
        return;
      }
      updateClassMember(1, this.selectedClassId, this.ids).then((response) => {
        this.$message({
          message: "添加成功",
          type: "success",
        });
        this.getList();
        this.addDialog2 = false;
        this.ids = [];
        this.selectedClassId = null;
      });
    },
    // 查看学习时长
    viewTime (row) {
      getStudyTime(row.id).then((res) => {
        this.studyTime = res.data.totalCost;
        this.timeDialog = true;
      });
    },
    //查看视频学习记录
    viewVideoRecord (row) {
      this.$router.push({
        name: "VideoRecord",
        query: {
          id: row.id,
          studentName: row.username,
        },
      });
    },
    //查看做题学习记录
    viewQuestionRecord (row) {
      this.$router.push({
        name: "QuestionRecord",
        query: {
          id: row.id,
          studentName: row.username,
        },
      });
    },
    //查看证书
    viewCertificates (row) {
      this.$router.push({
        name: "StudentCertificate",
        query: {
          id: row.id,
        },
      });
    },
    /** 修改信息按钮操作 */
    handleUpdate (row) {
      this.open = true;
      this.form = row;
    },
    /** 重置密码按钮操作 */
    handleResetPwd (row) {
      // this.$prompt('请输入"' + row.studentName + '"的新密码', "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   closeOnClickModal: false,
      //   inputPattern: /^.{5,20}$/,
      //   inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      // }).then(({ value }) => {
      //     resetUserPwd(row.userId, value).then(response => {
      //       this.$modal.msgSuccess("修改成功，新密码是：" + value);
      //     });
      //   }).catch(() => {});
    },
    /** 提交修改按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateInfo(this.form).then((response) => {
            this.open = false;
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      let that = this;
      const userIds = row.id || this.ids;
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项？', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //console.log(userIds)
          removeStudent(userIds).then((res) => {
            if (res.success == true) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              that.getList();
            } else {
              this.$message({
                message: "删除失败",
                type: "error",
              });
            }
          });
        })
        .catch(() => { });
    },
    // 删除选中学员
    handleDeleteSelected () {
      if (this.selectedRows.length > 0) {
        this.$confirm(`是否确认删除选中的${this.selectedRows.length}个学员？`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 用户点击了确定按钮，执行删除操作
          // 获取选中学员的id
          const ids = this.selectedRows.map(row => row.id);
          //console.log(ids)
          // 调用接口删除学员
          removeStudentSelected(ids).then((res) => {
            if (res.success == true) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getList();
            } else {
              this.$message({
                message: "删除失败",
                type: "error",
              });
            }
          });
        }).catch(() => {
          // 用户点击了取消按钮，不执行任何操作
        });
      } else {
        this.$message({
          type: "warning",
          message: "请先选择要删除的学员"
        });
      }
    },
    /** 导出按钮操作 */
    /* handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    }, */
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "批量导入学员";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$message({
        message: "导入成功",
        type: "success",
      });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
    // 文件上传超出个数限制处理
    handleFileExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length + fileList.length
        } 个文件，共选择了 ${files.length} 个文件`
      );
    },
    // 修改用户状态
    handleStatus (row) {
      this.form = row;
      this.form.isDisabled = row.isDisabled == true ? false : true;
      updateInfo(this.form).then((response) => {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.getList();
      });
    },
    //跳转页面
    goto: function (current) {
      this.page = current;
      this.getList();
    },
    //页码改变
    sizeChange: function (size) {
      this.limit = size;
      this.getList();
    },


    // 学员批量导出操作
    handleExport () {
      if (this.selectedRows.length > 0) {
        this.$confirm(`是否确认导出选中的${this.selectedRows.length}个学员？`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 用户点击了确定按钮，执行导出操作
          // 创建英文字段名到中文字段名的映射表
          const fieldMap = {
            id: '学号',
            username: '姓名',
            idcard: '身份证号',
            mobile: '联系电话',
            sex: '性别',
            age: '年龄',
            classname: '班级名称',
            subjectname: '工种',
            learnTime: '已学时长(分钟)',
            progress: '课程学习进度(%)',
            is_pass: '是否完成学习',
            isDisabled: '是否禁用',
            stateName: '学员状态',
            remark: '备注',
            grade: '职级'
            // 其他字段...
          };
          // 将英文字段名转化为中文字段名
          //console.log(this.selectedRows);
          const data = this.selectedRows.map(row => {
            const newRow = {};
            for (let key in row) {
              //如果key等于this.columns其中的value且this.columns中的visible为false,则使其跳出该层循环
              var flag = 0;
              for (let i = 0; i < this.columns.length; i++) {
                if (key === this.columns[i].value && this.columns[i].visible == false) {
                  flag = 1;
                  break;
                }
              }
              if (flag == 1) continue;
              //如果key等于avatar、classId、companyId、gmtCreate、gmtModified、nickname、openid、subjectId、password，则不导出
              if (key === 'avatar' || key === 'classId' || key === 'companyId' || key === 'gmtCreate' || key === 'gmtModified' || key === 'nickname' || key === 'openid' || key === 'subjectId' || key === 'password' || key === 'grade' || key === 'state' || key === 'isDeleted' || key === 'subjectParentId') {
                continue;
              }
              if (fieldMap[key]) {
                newRow[fieldMap[key]] = row[key];
              } else {
                newRow[key] = row[key];
              }
            }
            return newRow;
          });
          //console.log(this.selectedRows);
          //console.log(data);
          const worksheet = XLSX.utils.json_to_sheet(data);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, '学员信息');
          XLSX.writeFile(workbook, "学员信息.xlsx");

          Message.success('导出成功');
        }).catch(() => {
          // 用户点击了取消按钮，不执行任何操作
        });
      } else {
        this.$message({
          type: "warning",
          message: "请先选择要导出的学员"
        });
      }
    },

    // 学员全部导出操作
    handleExportAll () {
      // 判断allStudentList是否为空
      if (this.allStudentList.length == 0) {
        this.loading = true;
        getAllStudentList(this.queryParams, this.companyId).then((res) => {
          this.allStudentList = res.data.items;
          //console.log(this.allStudentList);
          this.selectedRows = []
          this.allStudentList.forEach((item) => {
            item.user.stateName = item.stateName;
            this.selectedRows.push(item.user);
          });
          //console.log(this.selectedRows);
          this.handleExport();
        })
        this.loading = false;
      } else {
        this.selectedRows = []
        this.allStudentList.forEach((item) => {
          item.user.stateName = item.stateName;
          this.selectedRows.push(item.user);
        });
        this.handleExport();
      }
    },

    // 按班级导入学员
    handleImportByClass(){
      this.upload2.title = "批量导入学员";
      this.upload2.open = true;
      /*this.upload2.url =
      process.env.BASE_API +
        "/eduM2/eduClass/batchImportClassStudent/" +
        this.companyId + '/' + this.classId;*/
    },
    // 文件上传中处理
    handleFileUploadProgress2 (event, file, fileList) {
      this.upload2.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess2 (response, file, fileList) {
      this.upload2.open = false;
      this.upload2.isUploading = false;
      this.$refs.upload2.clearFiles();
      this.$message({
        message: "导入成功",
        type: "success",
      });
      this.getList();
    },
    // 文件上传前处理 
    handleFileBefore(file){
		return new Promise((resolve, reject) => {
			// 拼接上传url
			// 此处动态配置action URL
      if (this.importClass == null) {
        this.$message({
          type: "warning",
          message: "请选择导入的班级"
        });
        reject();
        return false;
      }
      // 遍历classList，找到与importClass相同的id的那一项
      this.classList.forEach((item)=>{
        if(item.id == this.importClass){
          this.importInfo.companyId = item.companyId;
          this.importInfo.id = item.id;
          this.importInfo.subjectId = item.subjectId;
          this.importInfo.grade = item.grade;
        }
      })
			this.upload2.newurl = this.upload2.url +  this.importInfo.companyId + '/' + this.importInfo.id + '/' + this.importInfo.subjectId + '/' + this.importInfo.grade;
			// dom上传地址更新完成后，触发上传
			this.$nextTick(() => resolve());
		  });
	 },
    // 提交上传文件
    submitFileForm2 () {
      this.$refs.upload2.submit();
    },
    // 文件上传超出个数限制处理
    handleFileExceed2 (files, fileList) {
      // 判断是否选择了班级
      if (this.importClass == null) {
        this.$message({
          type: "warning",
          message: "请选择导入的班级"
        });
        return;
      }
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length + fileList.length
        } 个文件，共选择了 ${files.length} 个文件`
      );
    },


    // 筛选下拉框绑定工种子id
    handleCascaderChange (selectedValues) {
      // 获取最终选定的 children 的 id
      const finalSelectedId = selectedValues[selectedValues.length - 1];
      // 将其绑定到 queryParams.subjectId
      this.queryParams.subjectId = finalSelectedId;
    },

    //获取类别列表
    getCategoryList () {
      getCategory(0, this.companyId).then((res) => {
        const data = res.data;
        this.parentList = data.resList.map((item) => {
          return {
            label: item.courseName,
            id: item.id,
          }
        })
        //console.log(this.parentList)
        this.typeList = this.deleteChildren(data.resList);
      });
    },
    //删除类别列表中的空childrenList[]
    deleteChildren (arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].childrenList) {
          if (childs[i].childrenList.length) {
            this.deleteChildren(childs[i].childrenList);
          } else {
            delete childs[i].childrenList;
          }
        }
      }
      return arr;
    },

    // 获取班级列表
    getClassListMethod () {
      getClassList(this.companyId).then((res) => {
        this.classList = res.data.rows;
      });
    },
    //添加学生查询
    getAddList() {
      getUnClassStudentList(this.companyId, this.addQueryParams)
        .then((response) => {
          this.addQueryList = response;
          console.log(this.addQueryList);
        })
    },
    //重置添加学生查询
    resetAddList() {
      this.addQueryParams = {
        id: null,
        username: null,
        idcard: null,
        mobile: null,
      };
      this.getAddList();
    },
    //查询所有的职级
    getGradeList() {
      getGrade().then((res) => {
        if (res.success) {
          this.gradeList = res.data.resList;
          //console.log(this.gradeList)
        }
      });
    },
  },
};
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.el-icon-d-arrow-right {
  font-size: 12px;
}
</style>